package com.rem.chat.controller;

import com.rem.chat.aop.annotation.GlobalInterceptor;
import com.rem.chat.common.constants.Constants;
import com.rem.chat.common.utils.BeanTransUtil;
import com.rem.chat.common.utils.JacksonUtil;
import com.rem.chat.common.utils.RedisUtil;
import com.rem.chat.pojo.dataobject.GroupInfoDO;
import com.rem.chat.pojo.request.AddOrRemGroupUserRequest;
import com.rem.chat.pojo.request.GroupSaveRequest;
import com.rem.chat.pojo.response.CommonResult;
import com.rem.chat.pojo.response.GetGroupInfo4ChatResponse;
import com.rem.chat.pojo.response.GetGroupInfoResponse;
import com.rem.chat.pojo.response.LoadMyGroupResponse;
import com.rem.chat.service.AdminService;
import com.rem.chat.service.GroupService;
import com.rem.chat.service.dto.UserLoginDTO;
import com.rem.chat.service.enums.MessageTypeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author: Themberfue
 * @date: 2025/6/5 12:30
 * @description:
 */
@RestController("groupController")
@RequestMapping("/group")
@Validated
public class GroupController {
    private static final Logger log = LoggerFactory.getLogger(GroupController.class);

    @Resource
    RedisUtil redisUtil;

    @Resource(name = "groupServiceImpl")
    GroupService groupService;

    @Resource(name = "adminServiceImpl")
    AdminService adminService;

    @RequestMapping("/saveGroup")
    @GlobalInterceptor
    public CommonResult<Boolean> saveGroup(@RequestPart @Validated GroupSaveRequest param,
                                  MultipartFile avatarFile,
                                  MultipartFile avatarCover,
                                  HttpServletRequest request) throws IOException {
        log.info("saveGroup GroupSaveRequest：{}", JacksonUtil.writeValueAsString(param));

        // Step 1. 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        // Step 2. 构造群组信息
        GroupInfoDO groupInfoDO = BeanTransUtil.transToGroupInfoDO(param, user);

        return CommonResult.success(
                groupService.saveGroup(groupInfoDO, avatarFile, avatarCover));
    }

    @GetMapping("/loadMyGroup")
    @GlobalInterceptor
    public CommonResult<List<LoadMyGroupResponse>> loadMyGroup(HttpServletRequest request) {
        // Step 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        return CommonResult.success(
                groupService.loadMyGroup(user.getUserId()));
    }

    @GetMapping("/getGroupInfo")
    @GlobalInterceptor
    public CommonResult<GetGroupInfoResponse> getGroupInfo(HttpServletRequest request,
                                                           @NotEmpty String groupId) {
        log.info("getGroupInfo groupId：{}", groupId);

        // Step 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        return CommonResult.success(
                groupService.getGroupInfo(user, groupId));
    }

    @GetMapping("/getGroupInfo4Chat")
    @GlobalInterceptor
    public CommonResult<GetGroupInfo4ChatResponse> getGroupInfo4Chat(@NotEmpty String groupId) {
        log.info("getGroupInfo4Chat groupId：{}", groupId);

        return CommonResult.success(
                groupService.getGroupInfo4Chat(groupId));
    }

    @PostMapping("/addOrRemoveGroupUser")
    @GlobalInterceptor
    public CommonResult<Boolean> addOrRemoveGroupUser(@RequestBody @Validated AddOrRemGroupUserRequest param,
                                                      HttpServletRequest request) {
        log.info("addOrRemoveGroupUser AddOrRemGroupUserRequest：{}", JacksonUtil.writeValueAsString(param));

        // Step 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        if (param.getOpType().equals(Constants.ZERO)) {
            return CommonResult.success(
                    groupService.addGroup(user.getUserId(), param));
        } else {
            return CommonResult.success(
                    groupService.leaveGroup(user.getUserId(), param, MessageTypeEnum.REMOVE_GROUP));
        }
    }

    @DeleteMapping("/leaveGroup")
    @GlobalInterceptor
    public CommonResult<Boolean> leaveGroup(@NotNull String groupId, HttpServletRequest request) {
        log.info("leaveGroup groupId：{}", groupId);

        // Step 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        return CommonResult.success(
                groupService.leaveGroup(user.getUserId(), groupId, MessageTypeEnum.LEAVE_GROUP));
    }

    @DeleteMapping("/dissolutionGroup")
    public CommonResult<Boolean> dissolutionGroup(@NotNull String groupId, HttpServletRequest request) {
        log.info("dissolutionGroup groupId：{}", groupId);

        // Step 获取用户 Token (拦截器已经提前处理，无需做过多校验)
        UserLoginDTO user = getUserLoginDTO(request);

        return CommonResult.success(
                adminService.dissolutionGroup(groupId, user.getUserId()));
    }

    private UserLoginDTO getUserLoginDTO(HttpServletRequest request) {
        String token = request.getHeader("token");
        String user = redisUtil.get(Constants.REDIS_KEY_WS_TOKEN + token);
        log.info("user: {}", user);
        return JacksonUtil.readValue(user, UserLoginDTO.class);
    }
}
